package hu.bme.mit.rifl.business.base;

import hu.bme.mit.rifl.datamodel.Order;

import java.util.ArrayList;
import java.util.List;

/**
 * Base class for the worker nodes of the workflow. Implements the Runnable
 * interface and defines a common run method for the inheriting classes. Also
 * defines a default pull-return style interaction with the central coordinator
 * node.
 */
public abstract class WFElement {

	// The current Order work item.
	protected Order order;
	// Collections of queues for inputs and outputs.
	protected List<RiflOrderInputQueue> inputs;
	protected List<RiflOrderOutputQueue> outputs;

	/**
	 * Constructor with a reference to the central coordinator node.
	 * 
	 * @param title
	 *            title for the Swing window
	 */
	public WFElement(String title) {
		inputs = new ArrayList<RiflOrderInputQueue>();
		outputs = new ArrayList<RiflOrderOutputQueue>();
	}

	/**
	 * The actual business logic executed in the run method. Must be overridden
	 * by every inheriting node.
	 */
	public abstract void process();

	public boolean step() {
		pull();
		if (this.order != null) {
			process();
			finish();
			return true;
		}
		return false;
	}

	/**
	 * Getter for the current work item.
	 * 
	 * @return the current work item
	 */
	public Order getOrder() {
		return order;
	}

	/**
	 * Pulls the next available work item from the input queue of the node
	 * stored in the central coordinator.
	 */
	public void pull() {
		for (RiflOrderInputQueue queue : inputs) {
			this.order = queue.get();
			if (this.order != null)
				return;
		}
	}

	/**
	 * Returns the processed work item to the central coordinator.
	 */
	protected void finish() {
		outputs.get(0).put(this.order);
		this.order = null;
	}
}